package security.core.manager;

import security.core.source.UserDetail;
import security.core.source.service.UserSourceService;
import security.debug.RBACLogger;
import security.util.encryption.StringEncryptor;

public class AuthenticationManager {
	private UserSourceService userSourceService;
	private StringEncryptor passwordEncryptor;
	
	/*
	 * this method load an object of UserDetial by user name and validate the password(encryption enabled)
	 * for valid users, set the authorised roles(if no role is authorised, set an empty hash set) and then
	 * return the user detail object
	 * for invalid users, simply return null 
	 */
	public UserDetail authenticateUser(String username, String password) {
		if (RBACLogger.debug()) {
			RBACLogger.log("AuthenticationManager#authenticateUser is called!");
		}
		UserDetail user = userSourceService.loadUserByName(username);
		if (user != null && user.ValidatePassword(passwordEncryptor.encrypt(password))) {
			if (userSourceService.getUserRolesMap().containsKey(username)) {
				user.setAuthorisedRoles(userSourceService.getUserRolesMap().get(username));
			}
			return user;
		}

		return null;
	}

	// setters
	public void setUserSourceService(UserSourceService userSourceService) {
		this.userSourceService = userSourceService;
	}

	public void setPasswordEncryptor(StringEncryptor passwordEncryptor) {
		this.passwordEncryptor = passwordEncryptor;
	}
}
